package com.csxh.web.handler.eshop;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.csxh.web.model.BuyCart;
import com.csxh.web.model.BuyItem;
import com.csxh.web.model.eshop.Product;
import com.csxh.web.service.eshop.ProductService;
import com.csxh.web.util.servlet.WebUtil;


@Controller
@RequestMapping("/cart") // 请求的窄化处理
public class BuyCartHandler {

	@Autowired
	private ProductService productService;

	@RequestMapping("/list")
	public String listItem() {
		// 返回逻辑视图
		return "cart";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/add")
	public String addItem(HttpServletRequest request, int productId,
			@RequestParam(value = "quantity", defaultValue = "1") int quantity) {
		// 准备页面数据
		Product product = productService.findOneById(productId);

		BuyCart<BuyItem> buyCart = WebUtil.getBuyCart(request, BuyCart.class);

		BuyItem item = new BuyItem();

		item.setIsbn(product.getIsbn());
		item.setName(product.getName());
		item.setPrice(product.getPrice());
		item.setQuantity(quantity);
		item.setUnitWeight(product.getUnitWeight());
		buyCart.addItem(item);

		WebUtil.setBuyCart(request, buyCart);

		// 重定向到list处理器
		return "redirect:list.action";
	}

	@RequestMapping("/delete")
	public String deleteItem(Model model, HttpSession session, int itemId) {
		// 准备页面数据
		
		// 返回逻辑视图
		return "cart";
	}

	@RequestMapping("/update")
	public void updateItem(HttpServletRequest request,HttpServletResponse response, int[] itemIds, int[] quantitys) throws IOException {
		// 准备页面数据
		@SuppressWarnings({ "unchecked" })
		BuyCart<BuyItem> buyCart = WebUtil.getBuyCart(request, BuyCart.class);
		for(int i=0;i<itemIds.length;i++){
			int itemId=itemIds[i];
			int quantity=quantitys[i];
			buyCart.updateItem(itemId, quantity);
		}
		
		response.getWriter().append("true").flush();
		
	}

	@RequestMapping("/empty")
	public String emptyItem(Model model, HttpSession session) {
		// 准备页面数据

		// 返回逻辑视图
		return "cart";
	}

}
